package com.hanbang.taitaigou.ui.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.UserInforData;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.other.EditHelper;
import com.hanbang.taitaigou.utils.other.SharedPreferencesUtils;
import com.hanbang.taitaigou.utils.other.Validators;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

public class LogInActivity extends BaseActivity {

    // 验证码按钮倒计时 总时长和间隔时长
    private long totalTime = 60000, intervalTime = 1000;
    @ViewInject(R.id.code_button)
    private TextView codeButton;
    public static String FINISH_FLAG = "LogInActivity";

    private EditHelper editHelper = new EditHelper(this);

    private CheckBox cb_yzxy;
    private TextView tv_yzxy;

    private int ii = 1 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        initLocation();
        initView();
        setOnClickListener();
    }

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {
        findViewById(R.id.user_login_register_right).setOnClickListener(
                onClickListener);
        findViewById(R.id.user_login_forget_password).setOnClickListener(
                onClickListener);

        tv_yzxy.setOnClickListener(onClickListener);
        cb_yzxy.setOnClickListener(onClickListener);
    }

    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                case R.id.user_login_register_right:
                    intent.setClass(LogInActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 998);
                    break;
                case R.id.user_login_forget_password:
                    intent.setClass(LogInActivity.this,
                            ForgetPasswordActivity.class);
                    startActivity(intent);
                    break;
                case R.id.tv_yzxy:
                    intent.setClass(LogInActivity.this, AuthenticationProtocolActivity.class);
                    startActivity(intent);
                    break;
                case R.id.cb_yzxy:
                    selectCB(ii);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * checkBox点击事件
     */
    private void selectCB(int i){
        if(i == 1){
            cb_yzxy.setBackgroundResource(R.mipmap.check_box_no);
            cb_yzxy.setChecked(false);
            ii = 2;
        }else if(i == 2) {
            cb_yzxy.setBackgroundResource(R.mipmap.check_box_ok);
            cb_yzxy.setChecked(true);
            ii = 1;
        }
    }
    /*
     * 初始化view
     */
    private void initView() {
//        // 设置顶部的标题
//        setBackArrows(findViewById(R.id.top_bar_left));
//        setTop(null, R.mipmap.back, "用户登录", null, 0);
        // 设置顶部的标题
        setTop(null, 0, getString(R.string.user_Login), null, 0);
        setBackArrows(findViewById(R.id.top_bar_left_iv));


        editHelper.setEditText((EditText) findViewById(R.id.login_name),
                (EditText) findViewById(R.id.code));
        editHelper.setRegEx(Validators.REGEX_PHONE_NUMBER, "[\\S]{4,}");
        editHelper.setHintText("请正确输入手机号", "请正确输入验证码");

        cb_yzxy = (CheckBox) findViewById(R.id.cb_yzxy);
        tv_yzxy = (TextView) findViewById(R.id.tv_yzxy);


    }

    @Event(value = R.id.user_login_row, type = OnClickListener.class)
    private void loginOnClick(View view) {
        if (!editHelper.check()) {
            return;
        }
        if (!cb_yzxy.isChecked()) {
            ToastUtils.showShort(LogInActivity.this,"请同意验证协议...");
            return;
        }
        HttpRequestParams params = new HttpRequestParams();
        params.addBodyParameter("action", "UserLogin");
        params.addBodyParameter("mobile", editHelper.getText().get(0));
        params.addBodyParameter("code", editHelper.getText().get(1));
        params.addBodyParameter("user_type", "0");
        params.addBodyParameter("lng", String.valueOf(locationLng));
        params.addBodyParameter("lat", String.valueOf(locationLat));
        httpManager.post(params, new HttpCallBack<String>(this, "正在登录...", view) {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    if (json.getInt("status") == 1) {

                        userData = JsonHelper.parseObject(new JSONObject(json.getString("user_info")), UserInforData.class);

//                        String user_info= json.getString("user_info");
//                        userData = TimeUtils.subZhongTime(user_info);

                        try {
                            dbManager.saveOrUpdate(userData);
                            /**
                             * 保存成功 ， 把id放到sp里面
                             */
                            SharedPreferencesUtils.setSharedPreferencesKeyAndValue(LogInActivity.this, SharedPreferencesUtils.USER_DATA, "user_id", userData.getUser_id());
                            if (SharedPreferencesUtils.getSharedPreferencesKeyAndValue(LogInActivity.this, SharedPreferencesUtils.USER_DATA, "user_id", -1) != -1) {
                                //成功
                                ToastUtils.showShort(LogInActivity.this, json.getString("msg"));
                                ((MyApplication) getApplication()).getZuijin();
                                Intent intent = new Intent();
                                intent.setAction("LoginSuccess");
                                sendBroadcast(intent);
                                setResult(1001);
                                finish();
                            } else {
                                loninF();
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                            loninF();
                        }
                    } else {
                        ToastUtils.showShort(LogInActivity.this, json.getString("msg"));
                        userData = null;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    loninF();
                }
            }
        });

    }

    /**
     * 登录失败
     */
    private void loninF() {
        ToastUtils.showShort(this, "登录失败");
        userData = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 998 && resultCode == 999) {
            ((EditText) findViewById(R.id.login_name)).setText(data
                    .getStringExtra("phone"));
            ((EditText) findViewById(R.id.code)).setText(data
                    .getStringExtra("password"));
            loginOnClick(findViewById(R.id.user_login_row));
        }
    }

    /**
     * 发送注册验证码
     */
    @Event(value = R.id.code_button, type = OnClickListener.class)
    private void sendYZMClick(View view) {
        String mobile = editHelper.getText().get(0);

        if (!Validators.isPhoneNumber(mobile)) {
            UiUtils.shakeLeft(editHelper.getViewPostion(0), 0.9f, 10);
            ToastUtils.showLong(this, "请正确输入手机号");
            return;
        }


        HttpRequestParams params = new HttpRequestParams("UserVerifySmscode");
//        params.addBodyParameter("action", "UserVerifySmscode");
        params.addBodyParameter("code_type", "2");
        params.addBodyParameter("mobile", mobile);
        httpManager.post(params, new HttpCallBack<String>(this, "正在发送验证码...", view) {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    // {"status":1, "msg":"短信发送成功！","code":"9160"}
                    JSONObject json = new JSONObject(result);
                    ToastUtils.showShort(LogInActivity.this, json.getString("msg"));
                    if (json.getInt("status") == 1) {
                        countDownTimer.start();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        if (locationLat == 0 && locationLng == 0 && !mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        mLocationClient.unRegisterLocationListener(myListener);// 销毁监听，如果不销毁在退出是会报空指针异常
        super.onDestroy();
    }

    CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
        @Override
        public void onFinish() {// 计时完毕时触发
            codeButton.setText("重新发送");
            codeButton.setEnabled(true);
            // authCodeButton.setClickable(true);
        }

        @Override
        public void onTick(long currentTime) {// 计时过程显示
            // authCodeButton.setClickable(false);
            codeButton.setEnabled(false);
            codeButton.setText(currentTime / 1000 + "秒");
        }
    };

    /**
     * 设置定位参数包括：定位模式（高精度定位模式，低功耗定位模式和仅用设备定位模式），返回坐标类型，是否打开GPS，是否返回地址信息、位置语义化信息、
     * POI信息等等。
     */
    private void initLocation() {
        mLocationClient = new LocationClient(this); // 声明LocationClient类
        mLocationClient.registerLocationListener(myListener); // 注册监听函数


        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(false);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(false);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    /**
     * 类是定位SDK的核心类
     */
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    //经度
    private double locationLng;
    //纬度
    private double locationLat;

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation) {
                locationLng = location.getLongitude();
                locationLat = location.getLatitude();
            }
        }
    }

}
